import {Component, OnInit, ViewChild} from '@angular/core';
import {DeptSupervisionService} from './DeptSupervision.service';
import {NzMessageService, NzTreeSelectComponent} from 'ng-zorro-antd';
import {PageEntity} from '../../../core/domain/page.entity';
import {OtherUtil} from '../../../utils/other.util';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {StatusEnum} from '../../../core/enum/status.enum';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {FilterEnum, FilterTypeEnum} from '../../../core/enum/filter.enum';

@Component({
  selector: 'app-dept-supervision',
  templateUrl: './dept-supervision.component.html',
  styleUrls: ['./dept-supervision.component.scss'],
  providers: [DeptSupervisionService]
})
export class DeptSupervisionComponent implements OnInit {
  pageInfo: PageEntity = new PageEntity();
  searchParams: SearchParams = new SearchParams();
  dataList = [];
  mapOfCheckedId = {};
  isAllCheck = false;
  isIndeterminate = false;
  canDelete = true;
  isView = false;
  validateForm: FormGroup;
  formObj: FormObj = new FormObj();
  deptList = [];
  deptName = '';
  teacherPageInfo: PageEntity = new PageEntity();
  coursePageInfo: PageEntity = new PageEntity();
  teacherList = [];
  courseList = [];
  courseIdListEdit = [];
  constructor(
    private http: DeptSupervisionService,
    private message: NzMessageService,
    private fb: FormBuilder,
  ) { }

  ngOnInit() {
    this.page(this.pageInfo);
    this.getDeptList();
  }

  initForm() {
    this.validateForm = this.fb.group({
      deptId: [this.formObj.deptId, [Validators.required]],
      teacherId: [this.formObj.teacherId, [Validators.required]],
      courseIdList: [this.formObj.courseIdList, [Validators.required]]
    });
  }

  page(page) {
    this.http.page(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.dataList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }

  /**
   * 获取部门列表
   */
  getDeptList() {
    this.http.getDeptListApi().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.deptList = res.datas;
      }
    });
  }

  /**
   * 改变选择部门
   */
  changeDept(data) {
    if (!data) { return false; }
    this.formObj.deptId = data;
    this.teacherList = [];
    this.courseList = [];
    this.formObj.courseIdList = [];
    this.getTeacherList();
    this.getCourseList();
  }

  /**
   * 获取教师列表
   */
  getTeacherList() {
    this.teacherPageInfo.filters.orgId = PaginationUtils.filters(this.formObj.deptId, FilterEnum.EQUALS);
    this.teacherPageInfo.rows = 100;
    this.http.getTeacherListApi(this.teacherPageInfo).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.teacherList = res.datas.data;
      }
    });
  }

  /**
   * 获取课程列表
   */
  getCourseList() {
    this.coursePageInfo.filters.startDeptId = {
      matchMode: FilterEnum.EQUALS,
      value: this.formObj.deptId,
      whereType: FilterTypeEnum.AND
    };
    this.http.getCourseListApi(this.coursePageInfo).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.courseList = res.datas;
        const arr = [];
        res.datas.map(item => {
          if (this.courseIdListEdit.includes(item.id)) {
            arr.push(item.id);
          }
        });
        this.formObj.courseIdList = arr;
      }
    });
  }

  /**
   * 点击新增
   */
  clickAdd() {
    this.isView = true;
    this.formObj = new FormObj();
    this.initForm();
    this.teacherList = [];
    this.courseList = [];
    this.courseIdListEdit = [];
  }

  /**
   * 点击编辑
   */
  clickEdit(data) {
    this.isView = true;
    this.formObj = new FormObj();
    this.initForm();
    const courseIdList = [];
    data.courseList.map(item => {
      courseIdList.push(item.courseId);
    });
    this.formObj.deptId = data.deptId;
    this.courseIdListEdit = courseIdList;
    // this.formObj.courseIdList = courseIdList;
    this.formObj.teacherId = data.teacherId;
    this.formObj.id = data.id;
  }

  /**
   * 点击删除
   */
  deleteAll() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据!');
      return;
    }
    this.http.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.mapOfCheckedId = {};
        this.page(this.pageInfo);
      }
    });
  }

  clickDelete(id) {
    this.http.delete(id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  /**
   * 点击查询
   */
  clickSearch() {
    for (const o in this.searchParams) {
      if (this.searchParams[o]) {
        this.pageInfo.filters[o] = PaginationUtils.filters(this.searchParams[o], FilterEnum.CONTAINS);
      } else {
        delete this.pageInfo.filters[o];
      }
    }
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  /**
   * 点击重置
   */
  resetSearch() {
    this.searchParams = new SearchParams();
    this.pageInfo = new PageEntity();
    this.page(this.pageInfo);
  }

  /**
   * 改变第几页
   */
  changePageIndex(index: number) {
    this.pageInfo.first = index;
    this.page(this.pageInfo);
  }

  /**
   * 改变每页几条
   */
  changePageSize(size: number) {
    this.pageInfo.first = 1;
    this.pageInfo.rows = size;
    this.page(this.pageInfo);
  }

  /**
   * 点击保存
   */
  clickSave() {
    if (this.validateForm.valid) {
      if (this.formObj.id) {
        this.http.update(this.formObj).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.message.success(res.message);
            this.isView = false;
            this.pageInfo.first = 1;
            this.page(this.pageInfo);
          }
        });
      } else {
        this.http.create(this.formObj).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.message.success(res.message);
            this.isView = false;
            this.pageInfo.first = 1;
            this.page(this.pageInfo);
          }
        });
      }
    } else {
      this.message.error('请完善必填项');
    }
  }

  checkAll(value: boolean): void {
    this.dataList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  refreshStatus(): void {
    this.isAllCheck = this.dataList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.dataList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  cancelFn(): void {
    this.canDelete = true;
    this.isAllCheck = false;
    this.mapOfCheckedId = {};
    this.isIndeterminate = false;
  }
}

class SearchParams {
  deptName: string;
  teacherName: string;
  teacherNumber: number;
}


class FormObj {
  courseIdList: any;
  deptId: string;
  id: string;
  teacherId: string;
}
